<!--
导入导出Excel表格的操作

 * importCallBack 导入成功后的回调函数 返回的对象数组
 
 * export_json_to_excel({  //导出操作
    header: tHeader, //导出的表头
    data: dataArr,  //导出的数据
    filename: filenames, //文档名称
  });
-->
<template>
  <div class="import-content">
    <slot calss="limitHint"></slot>
    <img alt src="@/assets/images/common/uploadBg.jpg" class="uploadBg" />
    <div style="display: flex; margin-top: 40px; margin-bottom: 16px">
      <a-upload
        class="upload-demo"
        :action="actionUrl"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        :data="colData"
        :beforeUpload="beforeUpload"
        @change="handleChange"
        :file-list="fileList"
      >
        <a-button type="primary">{{
          $t('components.excelImport.footname')
        }}</a-button>
      </a-upload>
      <a-button class="downTemplate" @click="exportTemplate">{{
        $t('components.excelImport.dowlan')
      }}</a-button>
    </div>
  </div>
</template>
<script>
import { export_json_to_excel } from './export2Excel.js';
import { i18nRender } from '@/locales';
export default {
  name: 'excelImport',
  props: {
    templateName: {
      type: String,
      default: i18nRender('components.excelImport.templateName'),
    }, //导出的表格名称
    tHeader: {
      type: Array,
      required: true,
    }, //导出模板的表头信息
    filterVal: {
      type: Array,
      required: true,
    }, //表格的字段名称
    startRow: {
      type: Number,
      default: 1,
    }, //导入后从第几行开始解析数据
    maxImportLength: {
      type: Number,
      default: 500,
    }, //最大导入条数
  },
  data() {
    return {
      visible: false,
      limitUpload: 1,
      fileTemp: null,
      file: null,
      fileList: [],
      da: [],
      colData: {},
      dalen: 0,
      actionUrl: `/webproxy/common/excel/parse`,
    };
  },
  created() {
    this.colData = {
      parseData: JSON.stringify({
        cols: this.filterVal,
        startRow: this.startRow,
        maxRow: this.maxImportLength,
      }),
    };
  },
  methods: {
    showImport() {
      this.visible = true;
    },
    closeModal() {
      this.visible = false;
    },
    beforeUpload(file) {
      var fileTypeFlag = true;
      if (
        file.type !=
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' &&
        file.type != 'application/vnd.ms-excel'
      ) {
        fileTypeFlag = false;
      }
      if (!fileTypeFlag) {
        this.$message.warn(
          this.$t('components.excelImport.deleteAndUploadAgain')
        );
      }
      return fileTypeFlag;
    },
    handleChange(file) {
      this.fileTemp = file.file;
      if (this.fileTemp) {
        this.importCallBack([this.fileTemp]);
      } else {
        this.$message({
          type: 'warning',
          message: this.$t('components.excelImport.uploadAttach'),
        });
      }
    },
    handleRemove() {
      this.fileTemp = null;
    },
    //导入数据后的回调函数
    importCallBack(fileList) {
      if (!this.fileTemp.status) return; //有可能上次文件的格式不对，还是会进到这里
      if (this.fileTemp.status == 'done') {
        if (this.fileTemp.response.code == 0) {
          this.$emit('importCallBack', this.fileTemp.response.data.list);
          this.fileList = fileList;
          this.visible = false;
        } else if (this.fileTemp.response.code == -1) {
          top.location.href =
            this.fileTemp.response.ssoJump +
            '?back=' +
            encodeURIComponent(location.href);
        } else {
          this.fileList = [];
          if (this.fileTemp.response.code == -7) {
            this.$message.warning(
              this.$t('components.excelImport.maxDataLength', {
                num: this.maxImportLength,
              })
            );
          }
        }
      } else {
        this.fileList = fileList;
      }
    },
    //导出模板操作
    async exportTemplate() {
      var excelDatas = [
        {
          tHeader: this.tHeader, // sheet表一头部
          filterVal: this.filterVal, // 表一的数据字段
          tableDatas: [], // 表一的整体json数据
          sheetName: 'sheet1', // 表一的sheet名字
        },
      ];

      this.json2excel(excelDatas, this.templateName, true, 'xlsx');
    },
    // tableJson 导出数据 ; filenames导出表的名字; autowidth表格宽度自动 true or false; bookTypes xlsx & csv & txt
    json2excel(tableJson, filenames, autowidth, bookTypes) {
      let that = this;
      //这个是引用插件

      // 路径根据实际路径引入
      let tHeader = [];
      let dataArr = [];
      let sheetnames = [];
      for (var i in tableJson) {
        tHeader.push(tableJson[i].tHeader);
        dataArr.push(
          that.formatJson(tableJson[i].filterVal, tableJson[i].tableDatas)
        );
        sheetnames.push(tableJson[i].sheetName);
      }
      export_json_to_excel({
        header: tHeader,
        data: dataArr,
        sheetname: sheetnames,
        filename: filenames,
        autoWidth: autowidth,
        bookType: bookTypes,
      });
    },
    // 数据过滤，时间过滤
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
          //   if (j === 'timestamp') {
          //     return parseTime(v[j]);
          //   } else {

          //   }
        })
      );
    },
  },
};
</script>
<style lang="less" scoped>
.import-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .limitHint {
    margin-bottom: 10px;
  }
  .uploadBg {
    width: 60%;
  }
  .downTemplate {
    margin-left: 20px;
  }
}
</style>
